<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="renderer" content="webkit">
    <title></title>
    <link rel="stylesheet" href="__PUBLIC__/css/bootstrap.min.css">
    <link rel="stylesheet" href="__PUBLIC__/css/pintuer.css">
    <link rel="stylesheet" href="__PUBLIC__/css/admin.css">
    <link rel="stylesheet" href="__PUBLIC__/css/loading.css">
    <link rel="stylesheet" href="__PUBLIC__/css/goods-index.css?v=13.3">
    <link rel="stylesheet" href="__PUBLIC__/css/goods-add.css?v=3.1">
    <script src="__PUBLIC__/js/jquery.js"></script>
    <script src="__PUBLIC__/js/pintuer.js"></script>
    <script src="__PUBLIC__/js/dialog.js"></script>
    <script src="__PUBLIC__/js/loading.js"></script>
    <script src="__PUBLIC__/js/request.js"></script>
    <script src="__PUBLIC__/js/public.js?v=1"></script>
    <script src="__PUBLIC__/js/bootstrap.min.js"></script>
    <!--导出表格-->
    <script src="__PUBLIC__/js/jquery.table2excel.min.js"></script>
    <script type="text/javascript" src="__PUBLIC__/js/jquery.qrcode.js"></script>
    <script type="text/javascript" src="__PUBLIC__/js/utf.js"></script>
    <!-- 使用自定义的日期组件 -->
    <script type="text/javascript" src="__PUBLIC__/js/Calendar.js"></script>
    <!-- 富文本编辑器-->
    <!-- 配置文件 -->
    <script type="text/javascript" src="__PUBLIC__/thirdparty/ueditor/ueditor.config.js"></script>
    <!-- 编辑器源码文件 -->
    <script type="text/javascript" src="__PUBLIC__/thirdparty/ueditor/ueditor.all.js"></script>
    <style>
        #qrCodeShow {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            position: fixed;
            margin: 20px auto;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            border-radius: 10px;
            box-shadow: 0 0 30px #c1c1c1;
            background-color: rgba(0, 0, 0, 0.2);
        }
    </style>
</head>
<body>
<form id="goods_list" method="post" action="">
    <div class="panel admin-panel">
        <div class="panel-head"><strong class="icon-reorder"> 提问列表</strong>
        </div>
        <table id="id_table" class="table table-hover text-center">
            <tr>
                <th width="25%">商品</th>
                <th width="10%">价格</th>
                <th width="6%">销量</th>
                <th width="15%">状态</th>
                <th width="20%">截止日期</th>
                <th>操作</th>
                <th width="10%">二维码</th>
            </tr>

            <tr id="id_pages">
                <td colspan="8">
                    <div id="id_pagelist" class="pagelist">

                    </div>
                </td>
            </tr>
        </table>
    </div>
</form>
<!--商品编辑模板-->
<div id="container_goods_edit">
    <include file="./Public/template/template-goods-add.html"/>
</div>

<!--订单详情-->
<div id="order_detail" class="order-detail panel admin-panel">
    <div class="panel-head"><strong class="icon-reorder"> 订单详情</strong>
        <!--头部总结-->
        <div class="concusion-top">
            <div class="left">
                <div class="item">
                    成交总金额：<i id="statistic_orders_money_total"></i>
                </div>
                <div class="item">
                    成交总人数：<i id="statistic_orders_total"></i>
                </div>
                <div class="item">
                    团长人数：<i id="statistic_collage_header_total"></i>
                </div>
                <div class="item">
                    成团总数：<i id="statistic_collage_count_total"></i>
                </div>
            </div>
            <div class="right">
                <i id="order_detail_shop_name"></i>
                <i class="glyphicon glyphicon-remove" onclick="closeOrderDetail()">×</i>
            </div>
        </div>
    </div>
    <!-- 搜索-->
    <div class="search">
        <div class="search-item">
            <input type="text" placeholder="请输入姓名">
            <span>查询</span>
        </div>

        <div class="download fr">下载订单：<a href="javascript:;" id="download_excel"><i class="ico-xls"></i>Excel格式</a>
        </div>
        <!-- <i class="vs">|</i><a href="javascript:;" id="download_txt"><i class="ico-txt"></i>Txt格式</a>-->


    </div>
    <div class="orderData">
        <table id="id_table_orders" class="table text-center">
            <tr>
                <th width="10%">编号</th>
                <th width="15%">支付单号</th>
                <th width="10%">姓名</th>
                <th width="10%">微信昵称</th>
                <th width="10%">电话</th>
                <th width="9%">支付金额</th>
                <th width="5%">身份</th>
                <th width="8%">团购状态</th>
                <th width="8%">订单状态</th>
                <th width="12%">创建时间</th>
            </tr>

            <tr id="id_pages_orders">
                <td colspan="8">
                    <div id="id_pagelist_orders" class="pagelist">

                    </div>
                </td>
            </tr>
        </table>
    </div>

</div>
<!--二维码大图显示-->
<div class="container-qrCodeShow">
    <div id="qrCodeShow"/>
</div>
<script type="text/javascript">

    $('#qrCodeShow').hide();
    $('#qrCodeShow').click(function () {
        $(this).hide();
    });

    var order_show_goods_id,
        order_show_collage_start_count;

    var currentGoodsBeanEdit = {
        //商品信息
        goods_name: '',
        origin_price: '',
        current_price: '',
        collage_start_count: '',
        collage_price_header: '',
        collage_price_member: '',
        collage_price_back_to_header: '',
        collaged_count_forlook: '',
        goods_desc: '',
        head_imgs: [{
            type: 'addpic',
            uploadSuccess: true,
            img_url: 'Public/images/icon_addpic.png',
        }],
        dead_time: '',
        //店铺信息
        shop_name: '',
        shop_logo: '',
        shop_keyword: '',
        shop_address: '',
        shop_linkman: '',
        shop_contact_num: '',
        goods_share_msg: '',
    };
    var timer = null;
    var goodsBeanList = null, mOrderList = null, currentGoodsToExcel = null;
    var uEditor;
    var pageNo = 0;
    var pageSize = 10;


    var pageNo_orders = 0;
    var pageSize_orders = 500;
    $(function () {
        $('#container_goods_edit').hide();
        $('#add').html('<strong><span class="icon-pencil-square-o"></span> 编辑商品</strong>\n' +
            '        <div class="right-close">' +
            '            <i class="icon-close" onclick="closeGoodsEditDialog()">×</i>\n' +
            '        </div>');
        $('#btn_upload_data').text('保存');
        //加载第一页数据
        getGoodsList(pageNo);
        $('#download_excel').click(function () {
            //下载excel
            tableToExcel();
        });
        //实例化编辑器
        initUeditor();

        //保存按钮的点击事件
        $('#btn_upload_data').click(function () {
            submitEditData();
        });
    })


    function submitEditData() {
        loadingShow();
        //先上传图片
        var goodsImgs = currentGoodsBeanEdit.head_imgs;
        uploadGoodsHeadImgs(0, goodsImgs, function (goodsImgs) {
            currentGoodsBeanEdit.head_imgs = goodsImgs;

            var logo = currentGoodsBeanEdit.shop_logo + "";
            if (logo.indexOf("Public") == 0) {
                //开始上传大表单
                editGoods(currentGoodsBeanEdit, function (res) {
                    if (res) {
                        //定位到商品列表
                        top.location.href = "../index?nav=goodsList";
                    }
                    loadingHide();
                })
                return;
            }
            uploadShopLogo(currentGoodsBeanEdit.shop_logo, function (shop_logo) {
                if (!shop_logo) {
                    tip('店铺logo上传失败');
                    loadingHide();
                    return;
                }
                currentGoodsBeanEdit.shop_logo = shop_logo;
                //开始上传大表单
                editGoods(currentGoodsBeanEdit, function (res) {
                    if (res) {
                        //定位到商品列表
                        top.location.href = "../index?navTitlePos=goodsList&navChildPos=0";
                    }
                    loadingHide();
                })
            })
        });
    }


    //编辑商品
    function editGoods(goodsBean, cb) {
        //获取截止日期
        var val_dead_time = $('#dead_time').val();
        if (!val_dead_time) {
            tip('请选择截止日期');
            return;
        }
        goodsBean.deadTimeStr = val_dead_time;
        $.ajax({
            type: "POST",  //提交方式
            url: '/pintuan/admin/goods/editGoods',
            data: {
                goods_id: goodsBean.unique_id,
                goods_name: goodsBean.goods_name,
                origin_price: goodsBean.origin_price,
                collaged_count_forlook: goodsBean.collaged_count_forlook,
                goods_desc: goodsBean.goods_desc,
                head_imgs: JSON.stringify(goodsBean.head_imgs),
                dead_time: goodsBean.deadTimeStr,
                //店铺信息
                shop_name: goodsBean.shop_name,
                shop_logo: goodsBean.shop_logo,
                shop_keyword: goodsBean.shop_keyword,
                shop_address: goodsBean.shop_address,
                shop_linkman: goodsBean.shop_linkman,
                shop_contact_num: goodsBean.shop_contact_num,
                goods_share_msg: goodsBean.goods_share_msg
            },
            dataType: "json",
            success: function (res) { //返回数据根据结果进行相应的处理
                console.log(res);
                if (res.status != 200) {
                    typeof cb == "function" && cb(false)
                    tip(res.message);
                } else {
                    typeof cb == "function" && cb(true)
                }
            },
            error: function (e) {
                typeof cb == "function" && cb(false);
                tip('网络异常');
            }
        });
    }

    function uploadShopLogo(shopLogo, cb) {
        var formData = new FormData();
        // HTML 文件类型input，由用户选择
        formData.append("shop_logo", shopLogo);
        $.ajax({
            type: "POST",  //提交方式
            url: '/pintuan/admin/goods/uploadShopLogo',
            data: formData,
            dataType: "json",
            cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            success: function (res) { //返回数据根据结果进行相应的处理
                console.log(res);
                var data = res.data;
                if (res.status != 200) {
                    typeof cb == "function" && cb("")
                } else {
                    typeof cb == "function" && cb(data.imgPath);
                }
            },
            error: function (e) {
                typeof cb == "function" && cb("")
            }
        })
    }

    function uploadGoodsHeadImgs(index, goodsImgs, cb) {
        if (index >= goodsImgs.length - 1) {
            typeof cb == "function" && cb(goodsImgs)
            return;
        }
        var currentItem = goodsImgs[index];
        //递归上传图片
        if (currentItem.uploadSuccess) {
            index++;
            uploadGoodsHeadImgs(index, goodsImgs, cb);
            return;
        }

        var formData = new FormData();
        // HTML 文件类型input，由用户选择
        formData.append("goods_head_img", currentItem.img_url);
        $.ajax({
            type: "POST",  //提交方式
            url: '/pintuan/admin/goods/uploadGoodsImg',
            data: formData,
            dataType: "json",
            cache: false,//上传文件无需缓存
            processData: false,//用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            success: function (res) { //返回数据根据结果进行相应的处理
                console.log(res);
                var data = res.data;
                if (res.status != 200) {
                    goodsImgs[index].uploadSuccess = false;
                    index++;
                } else {
                    goodsImgs[index].uploadSuccess = true;
                    if (data.imgPath) {
                        goodsImgs[index].img_url = data.imgPath;
                    } else {
                        goodsImgs[index].img_url = "";
                    }
                    index++;
                }
                uploadGoodsHeadImgs(index, goodsImgs, cb);
            },
            error: function (e) {
                //上传失败
                goodsImgs[index].uploadSuccess = false;
                index++;
                uploadGoodsHeadImgs(index, goodsImgs, cb);
            }
        })
    }

    function initUeditor() {
        uEditor = UE.getEditor('container_ueditor', {
            autoHeightEnabled: false,
            autoFloatEnabled: false
        });
    }

    //关闭商品编辑对话框
    function closeGoodsEditDialog() {
        console.log(goodsBeanList);
        $('#goods_list').show();
        $('#container_goods_edit').hide();
    }

    function getGoodsList(pageIndex) {
//        loadingShow();
        pageNo = pageIndex;
        var params = {
            goods_state: 1,
            pageNo: pageNo,
            pageSize: pageSize,
        }
        $.ajax({
            url: '/pintuan/admin/goods/getGoodsList',
            data: params,
            dataType: "json",
            type: 'POST',
            success: function (data) {
                $('.tr-item').remove();
                var resData = data.data;
                if (!resData) {
                    return;
                }
                var resGoodsList = resData.goods_list;
                goodsBeanList = resGoodsList;
                var resStatus = data.status;
                if (resStatus == 200) {
                    var total_count = resData.total_count;
                    setPageList(Math.ceil(total_count / pageSize), pageNo, 'id_pagelist');
                    for (var i = 0; i < resGoodsList.length; i++) {
                        var goodsItem = resGoodsList[i];
                        var shopLogo = 'http://www.1688app.top/pintuan/' + goodsItem.shop_logo;
                        var content =
                            "<tr class='tr-item'>" +
                            "<td ><div class='view-shopinfo'>" +
                            " <div class='top'>" +
                            "<img src='" + shopLogo + "'" +
                            "alt=''/>" +
                            "<p>" + goodsItem.goods_name + "</p>" +
                            "" +
                            "</div><div class='bottom'>" +
                            "<div>店铺关键字</div>" +
                            "<div>" + goodsItem.shop_keyword + "</div>" +
                            "</div>" +
                            "</div></td>" +
                            "<td> <div class='collage-price-area'>" +
                            "<div class='collage-price-header'>" + goodsItem.collage_price_header + "元</div>" +
                            "<div class='collage-price-member'>" + goodsItem.collage_price_member + "元</div>" +
                            "</div></td>" +
                            "<td >" + goodsItem.order_count + "</td>" +
                            "<td ><div class='goods-state'>——</div></td>" +
                            "<td>" +
                            "<div class='goods-dead-time'" +
                            "<div>" +
                            timestampToTime(goodsItem.dead_time) +
                            "</div>" +
                            "<div  class='settime' endTime='" + goodsItem.dead_time + "' >" +
                            "00:00:00" +
                            "</div>" +
                            "</div></td>" +
                            "<td>" +
                            "<div class='goods-area-action'>" +
                            "<div class='top'>" +
                            "<div class='actionbg goods-edit' onclick='goodsEdit(" + i + ")'>编辑</div>" +
                            "<div  class='actionbg goods-offshelf' onclick='showModalOfflineGoods(" + i + ")' data-index='" + i + "' >" +
                            " 下架" +
                            "</div>"
                            +
                            "</div>" +
                            "<div class='actionbg bottom' onclick='showOrderDetail(" + i + "," + pageNo_orders + ")'>订单详情</div>" +
                            "</div>" +
                            "</td>" +
                            "<td>" +
                            "<div class='setqrCode' shopLogo='" + shopLogo + "' goodsId='" + goodsItem.unique_id + "'>" +

                            "</div>" +
                            "</td>" +
                            "</tr>";
                        $(content).insertBefore('#id_pages');
                    }
                    if (timer) {
                        clearTimeout(timer);
                    }
                    updateEndTime();
                    updateQrCode();
                } else {
                    tip(data.message);
                }
            },
            error: function () {
                tip('其他错误');
            },
            complete: function () {
//                loadingHide();
            }
        });
    }

    function setPageList(total_count, currrentPage, idName) {
        var content = "";
        var lastPage = "<a class='pageNoSelect' onclick='getGoodsList(" + (currrentPage - 1) + ")'>上一页</a>";
        var nextPage = "<a class='pageNoSelect' onclick='getGoodsList(" + (currrentPage + 1) + ")'>下一页</a>";
        content += currrentPage > 0 ? lastPage : '';
        for (var i = 0; i < total_count; i++) {
            var pageNum = i + 1;
            if (currrentPage == i) {
                content += "<span class='current'>" + pageNum + "</span>";
            } else {
                content += "<a class='pageNoSelect' onclick='getGoodsList(" + i + ")'>" + pageNum + "</a>";
            }
        }
        content += currrentPage >= total_count - 1 ? '' : nextPage;
        $('#' + idName).empty();
        $(content).appendTo($('#' + idName));

    }

    function goodsEdit(index) {
        $('#goods_list').hide();
        $('#container_goods_edit').show();
        console.log(index);
        let selectGoodsBean = goodsBeanList[index];
        currentGoodsBeanEdit['unique_id'] = selectGoodsBean['unique_id'];
        currentGoodsBeanEdit['goods_name'] = selectGoodsBean['goods_name'];
        currentGoodsBeanEdit['origin_price'] = selectGoodsBean['origin_price'];
        currentGoodsBeanEdit['current_price'] = selectGoodsBean['current_price'];
        currentGoodsBeanEdit['collage_start_count'] = selectGoodsBean['collage_start_count'];
        currentGoodsBeanEdit['collage_price_header'] = selectGoodsBean['collage_price_header'];
        currentGoodsBeanEdit['collage_price_member'] = selectGoodsBean['collage_price_member'];
        currentGoodsBeanEdit['collage_price_back_to_header'] = selectGoodsBean['collage_price_back_to_header'];
        currentGoodsBeanEdit['collaged_count_forlook'] = selectGoodsBean['collaged_count_forlook'];
        currentGoodsBeanEdit['dead_time'] = selectGoodsBean['dead_time'];
        currentGoodsBeanEdit['deadTimeStr'] = selectGoodsBean['deadTimeStr'];
        currentGoodsBeanEdit['goods_desc'] = selectGoodsBean['goods_desc'];
        currentGoodsBeanEdit['shop_name'] = selectGoodsBean['shop_name'];
        currentGoodsBeanEdit['shop_logo'] = selectGoodsBean['shop_logo'];
        currentGoodsBeanEdit['shop_keyword'] = selectGoodsBean['shop_keyword'];
        currentGoodsBeanEdit['shop_address'] = selectGoodsBean['shop_address'];
        currentGoodsBeanEdit['shop_linkman'] = selectGoodsBean['shop_linkman'];
        currentGoodsBeanEdit['shop_contact_num'] = selectGoodsBean['shop_contact_num'];
        currentGoodsBeanEdit['goods_share_msg'] = selectGoodsBean['goods_share_msg'];
        currentGoodsBeanEdit['head_imgs'] = selectGoodsBean['head_imgs'];


        currentGoodsBeanEdit['head_imgs'] = JSON.parse(currentGoodsBeanEdit['head_imgs']);
        //设置不可编辑的输入框的
        $("#current_price").attr("disabled", true);
        $("#collage_price_header").attr("disabled", true);
        $("#collage_price_member").attr("disabled", true);
        $("#collage_price_back_to_header").attr("disabled", true);
        $('input:radio[name="collage_start_count"]').attr('disabled', 'disabled');

        //对界面内容赋值
        $('#goods_name').val(currentGoodsBeanEdit['goods_name']);
        $('#dead_time').val(currentGoodsBeanEdit['deadTimeStr']);
        $('#origin_price').val(currentGoodsBeanEdit['origin_price']);
        $('#current_price').val(currentGoodsBeanEdit['current_price']);
        $('#collage_price_header').val(currentGoodsBeanEdit['collage_price_header']);
        $('#collage_price_member').val(currentGoodsBeanEdit['collage_price_member']);
        $('#collage_price_back_to_header').val(currentGoodsBeanEdit['collage_price_back_to_header']);
        $('#collaged_count_forlook').val(currentGoodsBeanEdit['collaged_count_forlook']);
        $('#shop_name').val(currentGoodsBeanEdit['shop_name']);
        $('#shop_keyword').val(currentGoodsBeanEdit['shop_keyword']);
        $('#shop_address').val(currentGoodsBeanEdit['shop_address']);
        $('#shop_linkman').val(currentGoodsBeanEdit['shop_linkman']);
        $('#shop_contact_num').val(currentGoodsBeanEdit['shop_contact_num']);
        $('#goods_share_msg').val(currentGoodsBeanEdit['goods_share_msg']);
        //商品图片回显
        goodsImgRedraw();
        //显示店铺图片
        $('#shopLogo').attr('src', 'http://www.1688app.top/pintuan/' + currentGoodsBeanEdit['shop_logo']);
        //商品描述回显
        //对编辑器的操作最好在编辑器ready之后再做
        uEditor.ready(function () {
            //设置编辑器的内容
            uEditor.setContent(currentGoodsBeanEdit['goods_desc']);
        });
        //回显几人团
        var collage_start_count = currentGoodsBeanEdit['collage_start_count'];
        if (collage_start_count == 2) {
            $('input:radio[name="collage_start_count"]').eq(0).attr("checked", true);
        } else if (collage_start_count == 3) {
            $('input:radio[name="collage_start_count"]').eq(1).attr("checked", true);
        } else if (collage_start_count == 5) {
            $('input:radio[name="collage_start_count"]').eq(2).attr("checked", true);
        } else if (collage_start_count == 7) {
            $('input:radio[name="collage_start_count"]').eq(3).attr("checked", true);
        }
    }

    function onShopImgChange(file) {
        if (!file.files || !file.files[0]) {
            return;
        }
        //给字段赋值
        currentGoodsBeanEdit['shop_logo'] = file.files[0]
        showLocalImage(file.files[0], $('#shopLogo'));
    }

    function selectShopImg() {
        $('#shopFile').trigger('click');
    }

    function OnTextInput(fieldname, event) {
        var value = $.trim(event.target.value);
        //如果是价格 都要转成float
        switch (fieldname) {
            case 'collaged_count_forlook':
                value = parseInt(value);
                break;
        }
        currentGoodsBeanEdit[fieldname] = value;
        console.log(currentGoodsBeanEdit);
    }

    function goodsImgRedraw() {
        let goodsHeadImgsEditArr = currentGoodsBeanEdit['head_imgs'];
        //遍历 head_imgs 数组
        $('#container_imgs').empty();
        $.each(goodsHeadImgsEditArr, function (index, element) {
            var opratorDiv = $("<div class='" + getOperatorClass(index >= goodsHeadImgsEditArr.length - 1) + "'><i onclick='goLeft(" + index + ")'> <<</i><i onclick='goRight(" + index + ")'>>> </i></div>");
            var deleteDiv = $("<div class='" + getOperatorDeleteClass(index >= goodsHeadImgsEditArr.length - 1) + "' onclick='deleteHeadImg(" + index + ")'>删除</div>");
            var imgUrl = element.img_url;//
            var uploadSuccess = element.uploadSuccess;
            var fileid = 'fileid_' + index;
            var el_file = $("<input type='file' onchange='f_change(this, " + index + ")'/>").attr('id', fileid).hide();
            var el_img = $('<img/>');
            var el_imgitem = $("<div class='item'></div>").append($(el_img));

            el_imgitem.append($(opratorDiv));
            el_imgitem.append($(deleteDiv));

            $(opratorDiv).hide();
            $(deleteDiv).hide();
            $(el_imgitem).hover(function () {
                $(opratorDiv).slideDown(500);
                $(deleteDiv).slideDown(500);
            }, function () {
                $(opratorDiv).slideUp(300);
                $(deleteDiv).slideUp(300);
            });

            $(el_imgitem).click(function (e) {
                if (index >= goodsHeadImgsEditArr.length - 1) {
                    //再次添加
                    $('#' + fileid).click();
                } else {
                    //删除

                }
            });
            if (uploadSuccess) {
                $(el_img).attr('src', 'http://www.1688app.top/pintuan/' + imgUrl);
            } else if (imgUrl) {
                showLocalImage(imgUrl, el_img);
            }
            $('#container_imgs').append($(el_imgitem)).append($(el_file));
        })
    }

    function deleteHeadImg(index) {
        currentGoodsBeanEdit['head_imgs'].splice(index, 1);
        goodsImgRedraw();
    }

    function getOperatorClass(isLast) {
        return isLast ? "oprator-none" : "oprator";
    }

    function getOperatorDeleteClass(isLast) {
        return isLast ? "oprator-none" : "oprator-delete";
    }

    function goLeft(index) {
        //判断index是否为0
        if (index == 0) {
            return;
        }
        //将这个条目取出来
        var currentItem = currentGoodsBeanEdit['head_imgs'][index];
        //将上一个条目取出来
        var preItem = currentGoodsBeanEdit['head_imgs'][index - 1];
        //将上一个条目删除，并替换成currentItem
        currentGoodsBeanEdit['head_imgs'].splice(index - 1, 1, currentItem);
        //将当前条目删除，并替换preItem
        currentGoodsBeanEdit['head_imgs'].splice(index, 1, preItem);
        goodsImgRedraw();
    }

    function goRight(index) {
        //判断index是否为最后一个条目
        if (index == currentGoodsBeanEdit['head_imgs'].length - 2) {
            return;
        }
        //将这个条目取出来
        var currentItem = currentGoodsBeanEdit['head_imgs'][index];
        //将下一个条目取出来
        var nextItem = currentGoodsBeanEdit['head_imgs'][index + 1];
        //将下一个条目删除，并替换成 currentItem
        currentGoodsBeanEdit['head_imgs'].splice(index + 1, 1, currentItem);
        //将当前条目删除，并替换 nextItem
        currentGoodsBeanEdit['head_imgs'].splice(index, 1, nextItem);
        goodsImgRedraw();
    }

    function showLocalImage(fileUri, el_img) {
        var reader = new FileReader();
        reader.onload = function (evt) {
            image = evt.target.result;
            $(el_img).attr('src', image);
        }
        reader.readAsDataURL(fileUri);
    }

    function f_change(file, index) {
        if (!file.files || !file.files[0]) {
            return;
        }
        //将图片url赋值给对应的item
        //将这个条目取出来
        var newItem = {
            type: "local",
            img_url: file.files[0]
        }

        var lastItem = currentGoodsBeanEdit['head_imgs'][currentGoodsBeanEdit['head_imgs'].length - 1];
        var new_head_imgs = [];
        $.each(currentGoodsBeanEdit['head_imgs'], function (index, element) {
            if (index < currentGoodsBeanEdit['head_imgs'].length - 1) {
                new_head_imgs.push(element);
            }
        })
        new_head_imgs.push(newItem);
        new_head_imgs.push(lastItem);
        currentGoodsBeanEdit['head_imgs'] = new_head_imgs;
        goodsImgRedraw();
    }

    function showModalOfflineGoods(index) {
        console.log(index);
        var goodsBean = goodsBeanList[index];
        var goods_id = goodsBean['unique_id'];
        $('#dialog_title').html('下架商品');
        $('#div_dialog_warntext').html(' <p>您确定要下架该商品吗？下架该商品可能会造成已有该商品订单用户无法获取相关优惠，请谨慎</p>');
        $('#div_dialog_confirm').click(function () {
            //下架该商品
            $('#myModal').modal('toggle')
//            loadingShow();
            $.ajax({
                    url: '/pintuan/admin/goods/goodsOffline',
                    data: {
                        'goods_id': goods_id
                    },
                    dataType: "json",
                    type: 'POST',
                    success: function (data) {
                        var resMsg = data.message;
                        var resStatus = data.status;
                        if (resStatus == 200) {
                            //刷新数据
                            getGoodsList(pageNo);
                            url = top.location.href; //把当前页面的地址赋给变量 url
                            top.location.replace(url); //刷新页面
                        } else {
                            tip(resMsg);
                        }
                    },
                    error: function () {
                        tip('其他错误');
                    },
                    complete: function () {
//                        loadingHide();
                        $('#div_dialog_confirm').unbind('click');
                    }

                }
            );
        });
        $('#myModal').modal('toggle')
    }


    //倒计时函数
    function updateEndTime() {
        var date = new Date();
        var time = Date.parse(date).toString();
        time = time.substr(0, 10);
        $(".settime").each(function (i) {
                var endTime = this.getAttribute("endTime"); //结束时间字符串
                var lag = (endTime - time); //当前时间和结束时间之间的秒数
                if (lag > 0) {
                    var second = Math.floor(lag % 60);
                    var minite = Math.floor((lag / 60) % 60);
                    var hour = Math.floor((lag / 3600) % 24);
                    var day = Math.floor((lag / 3600) / 24);
                    $(this).html(day + "天" + hour + "小时" + minite + "分" + second + "秒");
                    $(".goods-state").eq(i).html("销售中");
                    $(".goods-state").eq(i).removeClass("goods-state-saleout");
                    $(".goods-state").eq(i).addClass("goods-state-salling")
                } else {
                    $(this).html("团购已经结束啦！");
                    $(".goods-state").eq(i).html("已截止");
                    $(".goods-state").eq(i).removeClass("goods-state-salling");
                    $(".goods-state").eq(i).addClass("goods-state-saleout")
                }

            }
        );
        timer = setTimeout("updateEndTime()", 1000);
    }

    function updateQrCode() {
        $(".setqrCode").each(function (i) {
            var goodsId = this.getAttribute("goodsId").trim();
            var shopLogo = this.getAttribute("shopLogo").trim();
            jQuery('.setqrCode').eq(i).empty();
            jQuery('.setqrCode').eq(i).qrcode(
                {
                    render: "canvas",    //设置渲染方式，有table和canvas，使用canvas方式渲染性能相对来说比较好  
                    text: "https://www.1688app.top/pintuan/weixin?goodsId=" + goodsId,    //扫描二维码后显示的内容,可以直接填一个网址，扫描二维码后自动跳向该链接              
                    width: "600",            // //二维码的宽度             
                    height: "600",              //二维码的高度          
                    background: "#ffffff",       //二维码的后景色            
                    foreground: "#19BC45",        //二维码的前景色  
                    src: shopLogo           //二维码中间的图片          
                }
            );
            //设置点击事件
            jQuery('.setqrCode').eq(i).click(function () {
                $('#qrCodeShow').empty();
                $('#qrCodeShow').show();
                $('#qrCodeShow').qrcode(
                    {
                        render: "canvas",    //设置渲染方式，有table和canvas，使用canvas方式渲染性能相对来说比较好  
                        text: "https://www.1688app.top/pintuan/weixin?goodsId=" + goodsId,    //扫描二维码后显示的内容,可以直接填一个网址，扫描二维码后自动跳向该链接              
                        width: "400",            // //二维码的宽度             
                        height: "400",              //二维码的高度          
                        background: "#ffffff",       //二维码的后景色            
                        foreground: "#19BC45",        //二维码的前景色  
                        src: shopLogo           //二维码中间的图片          
                    }
                );
            });
        });
    }


    //关闭订单详情
    function closeOrderDetail() {
        pageNo_orders = 0;//厨师也为第一页
        $('#order_detail').hide();
        $('#goods_list').show();
    }

    //展示订单详情
    function showOrderDetail(index, pageIndex) {
        $('#order_detail').fadeIn(500, function () {

        });
        $('#goods_list').fadeOut(500, function () {

        });
        var goodsBean = goodsBeanList[index];
        currentGoodsToExcel = goodsBean;
        //请求该订单的订单详情
        order_show_goods_id = goodsBean['unique_id'];
        order_show_collage_start_count = goodsBean['collage_start_count'];
        var shop_name = goodsBean['shop_keyword'];
        $('#order_detail_shop_name').text(shop_name);//自动捕捉店铺关键字
//        loadingShow();
        $.ajax({
                url: '/pintuan/admin/order/getGoodsOrderList',
                data: {
                    'collage_start_count': order_show_collage_start_count,
                    'goods_id': order_show_goods_id,
                    pageNo: pageIndex,
                    pageSize: pageSize_orders,
                },
                dataType: "json",
                type: 'POST',
                success: function (data) {
                    var resMsg = data.message;
                    var resStatus = data.status;
                    var resData = data.data;
                    if (resStatus == 200) {
                        //统计数据展示在头部
                        $('#statistic_orders_money_total').text(resData.total_pay_price);
                        $('#statistic_orders_total').text(resData.total_pay_member_count);
                        $('#statistic_collage_header_total').text(resData.collage_header_count);
                        $('#statistic_collage_count_total').text(resData.collage_count_total);
                        //展示在界面上
                        var orderList = resData.order_list;
                        mOrderList = orderList;
                        $('.tr-item-orders').remove();
                        if (!orderList) {
                            return;
                        }
                        var total_count = resData.total_count;
//                        setOrderPageList(Math.ceil(total_count / pageSize_orders), pageIndex, 'id_pagelist_orders', index);
                        for (var i = 0; i < orderList.length; i++) {
                            var orderItemBean = orderList[i];
                            var collageCode = i < 9 ? '00' + (i + 1) : (i < 100 ? '0' + (i + 1) : i);
                            makeOrderRowView(orderItemBean, i, collageCode + '-01');
                            var collage_members = orderItemBean.collage_members;
                            if (!collage_members) {
                                continue;
                            }
                            for (var j = 0; j < collage_members.length; j++) {
                                var collageMemberBean = collage_members[j];
                                var code = j < 9 ? '0' + (j + 2) : (j + 2);
                                collageMemberBean['collageStateStr'] = orderItemBean['collageStateStr'];
                                makeOrderRowView(collageMemberBean, j, (collageCode) + '-' + code);
                            }
                        }
                    } else {
                        tip(resMsg);
                    }
                },
                error: function () {
                    tip('其他错误');
                },
                complete: function () {
//                    loadingHide();
                }

            }
        );

    }


    function setOrderPageList(total_count, currrentPage, idName, goodsIndex) {
        var content = "";
        var lastPage = "<a class='pageNoSelect' onclick='showOrderDetail(" + goodsIndex + "," + (currrentPage - 1) + ")'>上一页</a>";
        var nextPage = "<a class='pageNoSelect' onclick='showOrderDetail(" + goodsIndex + "," + (currrentPage + 1) + ")'>下一页</a>";
        content += currrentPage > 0 ? lastPage : '';
        for (var i = 0; i < total_count; i++) {
            var pageNum = i + 1;
            if (currrentPage == i) {
                content += "<span class='current'>" + pageNum + "</span>";
            } else {
                content += "<a class='pageNoSelect' onclick='showOrderDetail(" + goodsIndex + "," + i + ")'>" + pageNum + "</a>";
            }
        }
        content += currrentPage >= total_count - 1 ? '' : nextPage;
        $('#' + idName).empty();
        $(content).appendTo($('#' + idName));
    }


    function makeOrderRowView(orderItemBean, index, indexCode) {
        var content =
            "<tr class='tr-item-orders " + isRoleHeader(orderItemBean.role) + "'>" +
            "<td><img class='user-head-img' src='http://www.1688app.top/pintuan/" + orderItemBean.head_img + "'>" + indexCode + "</td>" +
            "<td>" + orderItemBean.out_trade_no + "</td>" +
            "<td>" + orderItemBean.user_name + "</td>" +
            "<td>" + orderItemBean.nick_name + "</td>" +
            "<td>" + orderItemBean.phone + "</td>" +
            "<td>" + orderItemBean.pay_price + "</td>" +
            "<td>" + getCollageRoleStr(orderItemBean.role) + "</td>" +
            "<td>" + orderItemBean.collageStateStr + "</td>" +
            "<td  class='" + getRoleClass(orderItemBean.role, orderItemBean.payStateStr) + "'>" + orderItemBean.payStateStr + "</td>" +
            "<td>" + orderItemBean.create_time + "</td>";

        $(content).insertBefore($('#id_pages_orders'));
    }

    function getdividerHeight(roleName) {
        var heightVal = 0;
        switch (roleName) {
            case "0":
                heightVal = 15;
                break
            case "1":
                heightVal = 15;
                break;

            case "2":
                heightVal = 0;
                break;
        }
        return heightVal;
    }

    function isRoleHeader(roleName) {
        if (roleName == '1') {
            return "role-header";
        } else if (roleName == '2') {
            return "role-member";
        } else if (roleName == "0") {
            return "role-dandugoumai";
        }
    }

    function getRoleClass(roleName, payStateStr) {
        if (!roleName) {
            return "";
        }
        var nameStr = '';
        if (payStateStr == '已支付') {
            switch (roleName) {
                case "0":
                    nameStr = "role-dandugoumai";
                    break;

                case "1":
                    nameStr = "role-header";
                    break;

                case "2":
                    nameStr = "role-member ";
                    break;
            }
        } else {
            if (payStateStr == '待支付') {
                nameStr = 'payWaiting';
            }

            if (payStateStr == '已取消') {
                nameStr = 'orderCancel';
            }
        }
        return nameStr;
    }

    function getCollageRoleStr(roleName) {
        if (!roleName) {
            return "";
        }
        var nameStr = '';
        switch (roleName) {
            case "0":
                nameStr = "单独购买";
                break;

            case "1":
                nameStr = "团长";
                break;

            case "2":
                nameStr = "团员";
                break;
        }
        return nameStr;
    }

    function tableToExcel() {
        $(".orderData").table2excel({
            // 不被导出的表格行的CSS class类
            exclude: ".noExl",
            // 导出的Excel文档的名称
            name: "Excel Document Name",
            // Excel文件的名称
            filename: "order",
            //文件后缀名
            fileext: ".xls",
            //是否排除导出图片
            exclude_img: true,
            //是否排除导出超链接
            exclude_links: false,
            //是否排除导出输入框中的内容
            exclude_inputs: false
        });
    }

    function tableToExceltest() {
        //列标题，逗号隔开，每一个逗号就是隔开一个单元格
        let str = `编号,支付单号,姓名,微信昵称,电话,支付金额,身份,团购状态,订单状态,创建时间\n`;
        for (let i = 0; i < mOrderList.length; i++) {
            let orderBean = mOrderList[i];
            var collageCode = i < 9 ? '00' + (i + 1) : (i < 100 ? '0' + (i + 1) : i);
            str += makeExcelStr(collageCode + '-01', orderBean);
            let members = orderBean.collage_members;
            for (let j = 0; j < members.length; j++) {
                let memberOrderBean = members[j];
                var code = j < 9 ? '0' + (j + 2) : (j + 2);
                str += makeExcelStr((collageCode) + '-' + code, memberOrderBean);
            }
        }
        //encodeURIComponent解决中文乱码
        let uri = 'data:text/xls;charset=utf-8,\ufeff' + encodeURIComponent(str);
        //通过创建a标签实现
        var link = document.createElement("a");
        link.style.width = '230px';
        link.href = uri;
        //对下载的文件命名
        link.download = currentGoodsToExcel.goods_name + '_' + formatTime(new Date(new Date().getTime()), 'yyyy_mm_dd hh:ii:ss') + ".xls";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    function makeExcelStr(code, orderBean) {
        let str = '';
        orderBean.roleNameStr = getCollageRoleStr(orderBean.role);
        //增加\t为了不让表格显示科学计数法或者其他格式
        str += `${code + '\t'},`;
        str += `${orderBean.out_trade_no + '\t'},`;
        str += `${orderBean.user_name + '\t'},`;
        str += `${orderBean.nick_name + '\t'},`;
        str += `${orderBean.phone + '\t'},`;
        str += `${orderBean.pay_price + '\t'},`;
        str += `${orderBean.roleNameStr + '\t'},`;
        str += `${orderBean.collageStateStr + '\t'},`;
        str += `${orderBean.payStateStr + '\t'},`;
        str += `${orderBean.create_time + '\t'},`;
        str += '\n';
        return str;
    }

    /**
     * 格式化时间字符串，支持Date对象
     * @param (Number) time 要格式化的时间串，或者是一个Date对象
     * @param (String) format 格式，如：yyyymmddhhiiss yyyy-mm-dd hh:ii:ss
     * @return (String) 格式化后的时间串
     */
    function formatTime(time /* Number */, format /* String */) {
        var
            y = format.findCount('y'),
            m = format.findCount('m'),
            d = format.findCount('d'),
            h = format.findCount('h'),
            i = format.findCount('i'),
            s = format.findCount('s');

        time = time || '';
        format = format || '';
        format = format.toLowerCase();
        if (time == '') {
            return time;
        }
        if (time.constructor == Date) {
            var tmp = '' + time.getFullYear() +
                ('00' + (time.getMonth() + 1)).slice(-2) +
                ('00' + time.getDate()).slice(-2) +
                ('00' + time.getHours()).slice(-2) +
                ('00' + time.getMinutes()).slice(-2) +
                ('00' + time.getSeconds()).slice(-2);
            time = tmp;
        }
        /*
        if(time.length <format.length){
            alert('要格式化的时间串与转换格式不一致！');
            return false;
        }
        */

        if (y > 0) {
            format = format.replace(copy('y', y), time.substring(0, 4).slice(-y));
        }

        if (m > 0) {
            format = format.replace(copy('m', m), ('00' + time.substring(4, 2)).slice(-m));
        }

        if (d > 0) {
            format = format.replace(copy('d', d), ('00' + time.substring(6, 2)).slice(-d));
        }

        if (h > 0) {
            format = format.replace(copy('h', h), ('00' + time.substring(8, 2)).slice(-h));
        }

        if (i > 0) {
            format = format.replace(copy('i', i), ('00' + time.substring(10, 2)).slice(-i));
        }

        if (s > 0) {
            format = format.replace(copy('s', s), ('00' + time.substring(12, 2)).slice(-s));
        }

        return format;
    }

    /**
     * 扩展String对象,添加查找字符串出现的次数
     * @param (String) str 要测试的字符串
     */
    String.prototype.findCount = function (str) {
        return this.split(str).length - 1;
    }

    /**
     * 复制字符串
     * @param (String) str 要复制的字符串
     * @param (String) num 要复制的次数
     * @return (Number) 复制后的字符串
     */
    function copy(str, num) {
        var tmp = '';
        for (var i = 0; i < num; i++) {
            tmp += str;
        }
        return tmp;
    }

</script>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="dialog_title"></h4>
            </div>
            <div id="div_dialog_warntext" class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button id="div_dialog_confirm" type="button" class="btn btn-primary">下架</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>